package org.example.y24.m12;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@SuppressWarnings("unused")
public class Net {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:11434/api/generate");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");

            String jsonInputString = "{\"prompt\": \"hello\", \"model\": \"deepseek-r1:14b\", \"stream\": true}";
            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = conn.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                String inputLine;
                boolean done;
                while ((inputLine = in.readLine()) != null) {
                    done = inputLine.contains("\"done\":true");
                    if (!done){
                        inputLine = inputLine.substring(inputLine.indexOf("\"response\":\"") + 12, inputLine.length() - 15);
                        inputLine = inputLine.replace("\\n", "\n");
                        if (inputLine.contains("\\u003c")){
                            inputLine = inputLine.replace("\\u003c", "\u003c");
                            inputLine = inputLine.replace("\\u003e", "\u003e");
                        }
                        System.out.print(inputLine);
                    }
                }
                in.close();
            } else {
                System.out.println("失败" + responseCode);
            }
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

